package com.demo.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @Created by xiangty on 2021/7/25
 */

class MyTask extends RecursiveTask<Integer> {

    // 拆分差值不能超过的阈值
    private static final Integer VALUE = 10;

    private int begin; // 最大值
    private int end; // 最小值
    private int result; // 返回值

    public MyTask(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        // 看两个数是否差值超过阈值
        if ((end - begin) <= VALUE) {
            for (int i = begin; i <= end; i++) {
                result += i;
            }
        } else {
            // 进一步拆分
            // 获取中间值
            int middle = (end + begin) / 2;
            // 拆分中间值左边
            MyTask myTask1 = new MyTask(begin, middle);
            // 拆分中间值右边
            MyTask myTask2 = new MyTask(middle + 1, end);
            // 调用方法拆分
            myTask1.fork();
            myTask2.fork();
            // 合并结果
            result = myTask1.join() + myTask2.join();
        }
        return result;
    }
}

public class ForkJoinDemo {
    public static void main(String[] argsa) {
        // 创建MyTask对象
        MyTask myTask = new MyTask(0, 100);
        // 创建分支合并池对象
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask forkJoinTask = forkJoinPool.submit(myTask);
        try {
            // 获取最终合并之后的结果
            System.out.println(forkJoinTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        // 关闭池对象
        forkJoinPool.shutdown();
    }
}
